package com.zhouyer.config;

import com.zhouyer.pojo.Configuration;
import com.zhouyer.pojo.MappedStatement;
import com.zhouyer.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        for (SqlCommandType value : SqlCommandType.values()) {
            // 解析所有的select
            List<Element> tagList = rootElement.selectNodes("//" + value.getTag());
            if (null != tagList && tagList.size() > 0) {
                for (Element element : tagList) {
                    String id = element.attributeValue("id");
                    String resultType = element.attributeValue("resultType");
                    String parameterType = element.attributeValue("parameterType");
                    String sql = element.getTextTrim();
                    MappedStatement mappedStatement = new MappedStatement();
                    mappedStatement.setId(id);
                    mappedStatement.setResultType(resultType);
                    mappedStatement.setParameterType(parameterType);
                    mappedStatement.setSql(sql);
                    mappedStatement.setSqlCommandType(value.getTag());
                    configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
                }
            }
        }

    }
}
